package com.udi.project.business.upload.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.udi.framework.config.udiConfig;
import com.udi.framework.web.domain.AjaxResult;
import com.udi.project.business.utils.excel.utils.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Admin
 * 错误文本
 */
@Component
@Slf4j
public class ErrorTest {

    @Autowired
    private Message message;

    /**
    *
     * @Description: 将DI申报失败的错误信息保存到文本
     * @param jsonObject 错误信息JSON格式
     * @return: JSONObject 消息
     * @Date: 2021/10/11 11:19
     */
    public AjaxResult error(JSONObject jsonObject) throws IOException{
        SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMddHHmmss");
        Date end = new Date();

        //文件名称
        String documentName = "医疗器械产品标识信息填报错误详情_"+dfs.format(end)+".txt";

        File file = new File(udiConfig.getDownloadPath()+documentName);

        BufferedWriter bw= new BufferedWriter(new FileWriter(udiConfig.getDownloadPath()+documentName));
        JSONObject obj = new JSONObject();
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("errorList"));
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                bw.newLine();
                bw.write(i+1+".最小销售单元产品标识："+jsonObject1.getString("ZXXSDYCPBS"));
                JSONArray msArray = JSONArray.parseArray(jsonObject1.getString("errorDetailList"));
                for (int y = 0; y < msArray.size(); y++){
                    JSONObject msgObject = msArray.getJSONObject(y);
                    bw.newLine();
                    bw.write("  "+(y+1)+".错误原因："+msgObject.getString("errorMsg"));
                }
                bw.write("\n");
            }
        if(file.exists()){
            bw.close();
            obj.put("returnMsg",jsonObject.getString("returnMsg"));
            obj.put("fileName",documentName);
            return AjaxResult.warn(obj.toString());
        }
        bw.close();
        log.info("DI错误信息文本存储失败，时间----》"+dfs.format(end));
        return AjaxResult.error("遇到错误，您的申报并未成功，我们无法将您填报的错误信息生成文本并下载，请联系管理员或稍后再试");
    }
}
